<!DOCTYPE html>
<html lang="zh-Hant">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width,initial-scale=1.0">
  <title>SmartPantry 食物管家</title>
  <style>
    :root {
      --main: #6aac6e;
      --main-dark: #4e8c51;
      --bg: #f6f8f2;
      --white: #fff;
      --accent: #e08e3b;
      --error: #d90429;
      --text: #2e2e2e;
      --shadow: 0 2px 10px rgba(106,172,110,.11);
      --radius: 18px;
      --transition: 0.22s;
      --footer-height: 62px;
      --skeleton: #e9ecdf;
    }
    html, body {
      margin:0; padding:0;
      background:var(--bg);
      color:var(--text);
      font-family:"PingFang TC", "Noto Sans TC", Arial, sans-serif;
      font-size: 17px;
      scroll-behavior: smooth;
    }
    body {
      min-height: 100vh;
      padding-bottom: var(--footer-height);
    }
    .hidden { display: none !important; }
    .header {
      background: linear-gradient(90deg, var(--main-dark) 0%, var(--main) 100%);
      color: var(--white);
      padding: 20px 0 14px 0;
      text-align: center;
      font-size: 2.25rem;
      font-weight: bold;
      letter-spacing: 2.6px;
      box-shadow: 0 1px 8px rgba(106,172,110,0.13);
      position: sticky;
      top: 0; left: 0; right: 0;
      z-index: 40;
      border-radius: 0 0 24px 24px;
      transition: background .2s;
    }
    .container {
      padding: 22px 2vw 12px 2vw;
      max-width: 750px;
      margin: auto;
    }
    .form-card {
      background: var(--white);
      border-radius: var(--radius);
      box-shadow: var(--shadow);
      padding: 28px 22px 23px 22px;
      margin-bottom: 24px;
      display: flex;
      flex-direction: column;
      gap: 19px;
      border: 1.5px solid #e6e6e6;
    }
    .form-group { display: flex; flex-direction: column; }
    label {
      font-weight: bold;
      margin-bottom: 6px;
      color: var(--main);
      letter-spacing: 1.2px;
    }
    input, select, textarea {
      width: 100%; padding: 11px 13px;
      border: 1.5px solid #c8e6c9;
      border-radius: 7px;
      font-size: 1.03rem;
      box-sizing: border-box;
      transition: border-color var(--transition), box-shadow var(--transition);
      background: #fafcf7;
      margin-bottom: 3px;
    }
    textarea { resize: vertical; min-height: 54px; }
    input:focus, select:focus, textarea:focus {
      border-color: var(--main);
      box-shadow: 0 0 0 2px #e2f5e1;
      outline: none;
    }
    .button, .btn-main {
      background: linear-gradient(90deg, var(--main-dark), var(--main));
      color: var(--white);
      border: none;
      padding: 14px 0;
      cursor: pointer;
      border-radius: 7px;
      font-size: 1.12rem;
      font-weight: bold;
      margin-top: 8px;
      box-shadow: 0 1px 5px rgba(106,172,110,0.09);
      transition: background var(--transition), opacity var(--transition);
      width: 100%;
      letter-spacing: 1.2px;
    }
    .button:disabled { opacity: 0.6; cursor: not-allowed; }
    .button:hover:enabled, .btn-main:hover:enabled { background:linear-gradient(90deg,var(--main), var(--main-dark)); }
    .input-error { border-color: var(--error)!important; }
    .error-text { color: var(--error); font-size: 0.95em; margin-top:2px;}
    .success-message, .error-message {
      padding: 12px; border-radius: 7px; margin-bottom: 17px; text-align: center;
      display: none;
      font-size: 1em;
    }
    .success-message { background: rgba(106,172,110,0.14); color: var(--main);}
    .error-message { background: rgba(217,4,41,0.11); color: var(--error);}
    /* 底部導航欄 */
    .footer-nav {
      position: fixed; left: 0; right: 0; bottom: 0;
      height: var(--footer-height);
      background: var(--white);
      border-top: 1.5px solid #e6e6e6;
      display: flex;
      justify-content: space-around;
      align-items: center;
      z-index: 100;
      box-shadow: 0 -2px 12px #e7e7e7;
      border-radius: 16px 16px 0 0;
    }
    .footer-nav button {
      background: none; border: none;
      padding: 0; margin: 0 4px;
      flex: 1; color: #7b8e7f;
      font-size: 1.11rem;
      display: flex; flex-direction: column; align-items: center;
      cursor: pointer; transition: color .2s;
      outline: none;
      font-weight: 600;
    }
    .footer-nav .active { color: var(--main);}
    .footer-nav svg { font-size: 1.45em; margin-bottom: 2px; }
    /* 卡片、列表等 */
    .card, .food-card, .reminder-card, .list-item, .recipe-card, .chat-message {
      background: var(--white);
      border-radius: var(--radius);
      box-shadow: var(--shadow);
      padding: 19px 14px 14px 16px;
      margin-bottom: 17px;
      border: 1px solid #f0f0f0;
      transition: box-shadow .18s;
    }
    .food-card img, .market-food-img {
      width: 100%; height: 170px; object-fit: cover; border-radius: 10px; margin-bottom: 8px;
      background: var(--skeleton);
      transition: opacity .2s;
    }
    .food-card .content { padding-top: 6px; }
    .food-card .title { font-weight: bold; font-size: 1.13rem; margin-bottom: 3px;}
    .food-card .details { font-size: 0.97rem; color: #666; margin-bottom: 7px;}
    .food-card .timer { font-size: 0.98rem; color: #e63946; margin-bottom: 11px;}
    .food-card .actions { display: flex; justify-content: space-between; align-items: center;}
    /* 主頁動態消息 */
    .feed-post {
      background: var(--white);
      border-radius: var(--radius);
      padding: 16px 14px;
      margin-bottom: 15px;
      box-shadow: 0 2px 8px rgba(106,172,110,0.09);
      display: flex; gap: 14px; align-items: flex-start;
      border: 1px solid #f0f0f0;
    }
    .feed-avatar {
      width: 54px; height: 54px; border-radius: 50%; background: #d3ecd4;
      display: flex; align-items: center; justify-content: center; font-size: 1.6rem;
      border: 2px solid #e6e6e6;
    }
    .feed-content { flex: 1; }
    .feed-content .feed-user { font-weight: bold; color: #4e8c51; font-size: 1.07em;}
    .feed-content .feed-text { margin: 6px 0; font-size: 1em;}
    .feed-actions { display: flex; align-items: center; gap: 18px; font-size: 1em;}
    .feed-actions button { background: var(--main); border: none; color: #fff; cursor: pointer; font-weight: bold; border-radius: 6px; padding:6px 19px;}
    .feed-image { max-width: 120px; border-radius: 9px; margin-top: 7px; box-shadow:0 1px 6px #e6e6e6;}
    /* popup遮罩 */
    .mask {
      position: fixed; left: 0; top: 0; right: 0; bottom: 0;
      background: rgba(0,0,0,0.12);
      z-index: 999;
      display: flex; justify-content: center; align-items: center;
    }
    /* 其它樣式 */
    .section-title {
      font-size: 1.29rem;
      font-weight: bold;
      color: var(--main-dark);
      margin-bottom: 15px;
      border-left: 5px solid var(--accent);
      padding-left: 12px;
      letter-spacing: 1.3px;
    }
    .map { width: 100%; height: 180px; background: #e2e2e2; display: flex; align-items: center; justify-content: center; font-size: 19px; color: #666; margin-bottom: 21px; border-radius: 11px;}
    .profile-header {
      display: flex; align-items: center; gap: 22px; margin-bottom: 20px;
    }
    .profile-header img { width: 74px; height: 74px; border-radius: 50%; border: 3px solid var(--main);}
    .profile-header .name { font-size: 1.25rem; font-weight: bold; color: var(--main);}
    .tabs { display: flex; justify-content: space-around; border-bottom: 2px solid #efefef; margin-bottom: 21px;}
    .tabs button {
      flex: 1; padding: 11px;
      font-size: 1.04rem;
      background: var(--accent);
      color: white;
      border: none;
      border-radius: 7px 7px 0 0;
      cursor: pointer;
      outline: none;
      font-weight: bold;
      margin-right: 3px;
      transition: background .15s;
    }
    .tabs button.active { background: var(--main);}
    .tab-content { display: none; padding: 12px 0;}
    .tab-content.active { display: block;}
    .settings button {
      background-color: var(--accent);
      color: white;
      border: none;
      padding: 10px 15px;
      border-radius: 7px;
      font-size: 1.04rem;
      cursor: pointer;
      margin-bottom: 11px;
      display: block;
      width: 100%;
      text-align: left;
      letter-spacing: 1.1px;
    }
    /* 聊天窗 */
    .market-chat-modal {
      position:fixed;top:0;left:0;right:0;bottom:0;z-index:9999;
      background:rgba(0,0,0,0.13);
      display:flex;align-items:center;justify-content:center;
    }
    .market-chat-window {
      background:#fff;border-radius:16px;max-width:380px;width:97vw;
      box-shadow:0 2px 28px #aaa;padding:0 0 18px 0;position:relative;display:flex;flex-direction:column;
      max-height:82vh;
      overflow:hidden;
    }
    .market-chat-header {
      background: linear-gradient(90deg, var(--main-dark), var(--main));
      color:#fff;padding:16px 18px;font-weight:bold;border-top-left-radius:16px;border-top-right-radius:16px;
      font-size:1.13em;display:flex;align-items:center;justify-content:space-between;
    }
    .market-chat-messages {
      padding: 12px 16px;flex:1;overflow-y:auto;display:flex;flex-direction:column;gap:9px;background:#f8fcf4;
    }
    .chat-message {
      background: #e9f7e7;
      border-radius: 15px;
      padding: 8px 12px;
      max-width: 78%;
      font-size: 0.99em;
      align-self: flex-start;
      margin-bottom: 0;
    }
    .chat-message.self {background: #f4b774; color:#fff; align-self: flex-end;}
    .market-chat-input-area {
      display:flex;gap:8px;padding:8px 14px 0 14px;background:#fff;
    }
    .market-chat-input-area input {
      flex:1; font-size:1em; border-radius:10px; border:1px solid #dbeed3; padding:8px 12px;
      background: #f9f9f9;
    }
    .market-chat-input-area button {
      background:var(--main);color:#fff;border:none;border-radius:8px;padding:8px 19px;font-weight:bold;cursor:pointer;
      transition:background .15s;font-size:1.03em;letter-spacing:1.1px;
    }
    /* 響應式 */
    @media (max-width: 600px) {
      .header { font-size: 1.4rem; padding: 13px 0;}
      .container { padding: 12px 2vw 10px 2vw;}
      .profile-header img { width: 60px; height: 60px;}
      .footer-nav { height: 56px;}
    }
  </style>
</head>
<body>
  <!-- header -->
  <div id="main-header" class="header">SmartPantry 食物管家</div>

  <!-- 登入/註冊介面 -->
  <div id="page-login" class="container">
    <div id="login-success" class="success-message"></div>
    <div id="login-error" class="error-message"></div>
    <!-- 登入表單 -->
    <form class="form-card" id="login-form" autocomplete="off">
      <div class="form-group">
        <label for="login-email">電子郵件 <span style="color:#d90429;">*</span></label>
        <input type="email" id="login-email" required placeholder="請輸入您的電子郵件">
        <div class="error-text" id="loginEmailError"></div>
      </div>
      <div class="form-group">
        <label for="login-password">密碼 <span style="color:#d90429;">*</span></label>
        <input type="password" id="login-password" required placeholder="請輸入您的密碼">
        <div class="error-text" id="loginPasswordError"></div>
      </div>
      <button class="button" id="login-btn" type="submit">登入</button>
      <div class="toggle-form" style="text-align:center;">
        還沒有帳號？<a href="#" id="to-register">立即註冊</a>
      </div>
    </form>
    <!-- 註冊表單 -->
    <form class="form-card hidden" id="register-form" autocomplete="off">
      <div class="form-group">
        <label for="register-name">姓名 <span style="color:#d90429;">*</span></label>
        <input type="text" id="register-name" required placeholder="請輸入您的姓名">
        <div class="error-text" id="registerNameError"></div>
      </div>
      <div class="form-group">
        <label for="register-email">電子郵件 <span style="color:#d90429;">*</span></label>
        <input type="email" id="register-email" required placeholder="請輸入您的電子郵件">
        <div class="error-text" id="registerEmailError"></div>
      </div>
      <div class="form-group">
        <label for="register-password">密碼 <span style="color:#d90429;">*</span></label>
        <input type="password" id="register-password" required placeholder="請輸入密碼（至少6個字符）">
        <div class="error-text" id="registerPasswordError"></div>
      </div>
      <div class="form-group">
        <label for="register-confirm">確認密碼 <span style="color:#d90429;">*</span></label>
        <input type="password" id="register-confirm" required placeholder="請再次輸入密碼">
        <div class="error-text" id="registerConfirmError"></div>
      </div>
      <button class="button" id="register-btn" type="submit">註冊</button>
      <div class="toggle-form" style="text-align:center;">
        已有帳號？<a href="#" id="to-login">立即登入</a>
      </div>
    </form>
  </div>

  <!-- 主頁（動態/分享） -->
  <div id="page-feed" class="container hidden">
    <div style="display:flex; align-items:center; justify-content:space-between; margin-bottom: 10px;">
      <div class="section-title" style="border:none; padding-left:0;">動態分享</div>
    </div>
    <div class="section-title">每日推薦食譜</div>
    <div id="feed-recipes"></div>
    <div class="section-title" style="margin-top:18px;">分享動態</div>
    <div id="feed-stream"></div>
    <button class="btn-main" style="margin:22px 0 0 0;" onclick="showPostPopup()">我要分享/發佈</button>
  </div>

  <!-- 食譜生成器 -->
  <div id="page-recipe" class="container hidden">
    <div class="section-title">智慧食譜生成器</div>
    <form class="form-card" id="recipeForm" autocomplete="off" novalidate>
      <div class="form-group">
        <label for="age">年齡 <span style="color:#d90429;">*</span></label>
        <input type="number" id="age" name="age" placeholder="請輸入您的年齡" min="1" max="120" required>
        <div class="error-text" id="ageError"></div>
      </div>
      <div class="form-group">
        <label for="allergens">過敏原</label>
        <input type="text" id="allergens" name="allergens" placeholder="請輸入過敏原（例如：堅果、乳製品）">
      </div>
      <div class="form-group">
        <label for="goal">飲食目標</label>
        <select id="goal" name="goal">
          <option value="lose-weight">減脂</option>
          <option value="gain-muscle">增肌</option>
          <option value="maintain">保持健康</option>
        </select>
      </div>
      <div class="form-group">
        <label for="cuisineType">你想做什麼類型的菜式？</label>
        <select id="cuisineType" name="cuisineType">
          <option value="Chinese">中式</option>
          <option value="Western">西式</option>
          <option value="Vegetarian">素食</option>
        </select>
      </div>
      <div class="form-group">
        <label for="prepTime">你希望這個食譜的準備時間大約是多久？</label>
        <select id="prepTime" name="prepTime">
          <option value="30">30分鐘</option>
          <option value="60">1小時</option>
          <option value="120">2小時</option>
        </select>
      </div>
      <div class="form-group">
        <label for="ingredients">你打算用什麼食材？</label>
        <input type="text" id="ingredients" name="ingredients" placeholder="例如：雞肉、番茄">
      </div>
      <div class="form-group">
        <label for="servings">你有幾個人需要這道菜？</label>
        <select id="servings" name="servings">
          <option value="1">1人</option>
          <option value="2">2人</option>
          <option value="4">4人</option>
          <option value="6">6人以上</option>
        </select>
      </div>
      <button class="button" id="generate" type="submit">生成食譜</button>
    </form>
    <div id="loading-message" class="success-message" style="display:none;">生成中，請稍候...</div>
    <div id="error-message" class="error-message" style="display:none;"></div>
    <div class="section-title" id="recipe-section-title" style="display:none;">推薦食譜</div>
    <div id="recipe-container"></div>
  </div>

  <!-- 食物掃描與管理 -->
  <div id="page-scan" class="container hidden">
    <div class="section-title">掃描或新增食物</div>
    <div class="scanner" style="display:flex; gap:10px; margin-bottom:16px;">
      <button class="btn-main" onclick="alert('此功能僅示意，可接相機API')">掃描條碼</button>
      <button class="btn-main" onclick="alert('此功能僅示意，可接相機API')">拍攝包裝</button>
    </div>
    <div class="section-title">手動新增</div>
    <div class="form-card" style="margin-bottom:13px;">
      <div class="form-group">
        <label for="food-name">食物名稱</label>
        <input type="text" id="food-name" placeholder="例如：牛奶、雞蛋">
      </div>
      <div class="form-group">
        <label for="expiry-date">到期日</label>
        <input type="date" id="expiry-date">
      </div>
      <div class="form-group">
        <label for="quantity">數量</label>
        <input type="number" id="quantity" placeholder="例如：1, 2">
      </div>
      <div class="form-group">
        <label for="food-photo">照片（可選）</label>
        <input type="file" id="food-photo" accept="image/*">
      </div>
      <button class="btn-main" type="button" id="add-food-btn">新增食物</button>
    </div>
    <div class="section-title">即將到期</div>
    <div id="scan-reminder-list"></div>
  </div>

  <!-- 食物分享市集 -->
  <div id="page-market" class="container hidden">
    <div class="section-title">附近的食物分享</div>
    <div class="map">地圖占位符（可整合地圖API）</div>
    <div class="section-title">可分享的食物</div>
    <div id="market-food-list"></div>
  </div>

  <!-- 個人檔案 -->
  <div id="page-profile" class="container hidden">
    <div class="profile-header">
      <img id="profile-avatar" src="https://via.placeholder.com/80x80" alt="頭像">
      <div>
        <div class="name" id="profile-name">用戶名稱</div>
      </div>
    </div>
    <div class="tabs">
      <button id="tab-recipes" class="tab-button active" onclick="showProfileTab('recipes')">我的食譜</button>
      <button id="tab-shared" class="tab-button" onclick="showProfileTab('shared')">分享紀錄</button>
    </div>
    <div id="profile-recipes" class="tab-content active"></div>
    <div id="profile-shared" class="tab-content"></div>
    <div class="section-title">設定</div>
    <div class="settings">
      <button onclick="alert('健康資料更新功能敬請期待')">更新健康資料</button>
      <button onclick="alert('通知功能敬請期待')">通知開關</button>
      <button onclick="logout()">登出</button>
    </div>
  </div>

  <!-- 發佈動態/分享 Popup -->
  <div id="post-popup" class="mask hidden" style="z-index:2000;">
    <div style="background:#fff; border-radius:14px; padding:28px 20px 17px 20px; box-shadow:0 2px 24px #999; max-width:360px; width:95vw; position:relative;">
      <button style="position:absolute; right:11px; top:11px; background:none; border:none; color:#888; font-size:1.3em; cursor:pointer;" onclick="hidePostPopup()">✖</button>
      <div style="font-weight:bold; color:#6aac6e; font-size:1.15em; margin-bottom:12px;">發佈分享/動態</div>
      <input id="post-photo" type="file" accept="image/*" style="margin:0 0 9px 0;">
      <textarea id="post-content" rows="3" placeholder="請輸入分享內容..." style="width:100%; border-radius:7px; border:1px solid #ddd; font-size:1em; padding:8px;"></textarea>
      <button class="btn-main" style="margin-top:13px;" onclick="submitPost()">發佈</button>
    </div>
  </div>

  <!-- 市集聊天彈窗 -->
  <div id="market-chat-modal" class="market-chat-modal hidden">
    <div class="market-chat-window">
      <div class="market-chat-header">
        <span id="chat-title">與分享者聊天</span>
        <button style="background:none;border:none;color:#fff;font-size:1.3em;cursor:pointer;" onclick="closeMarketChat()">✖</button>
      </div>
      <div class="market-chat-messages" id="chat-messages"></div>
      <div class="market-chat-input-area">
        <input type="text" id="chat-input" placeholder="輸入訊息...">
        <button onclick="sendMarketMessage()">送出</button>
      </div>
    </div>
  </div>

  <!-- 底部導航欄 -->
  <nav class="footer-nav" id="footer-nav" style="display:none;">
    <button id="nav-feed" onclick="switchPage('feed')" class="active">
      <svg viewBox="0 0 24 24" fill="none" width="25" height="25"><path d="M5 12h14M5 6h14M5 18h14" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>
      <span>動態</span>
    </button>
    <button id="nav-market" onclick="switchPage('market')">
      <svg viewBox="0 0 24 24" width="25" height="25" fill="none"><circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2"/><path d="M7 16l5-5 5 5" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>
      <span>市集</span>
    </button>
    <button id="nav-scan" onclick="switchPage('scan')">
      <svg viewBox="0 0 24 24" width="25" height="25" fill="none"><rect x="3" y="3" width="6" height="6" rx="1.5" stroke="currentColor" stroke-width="2"/><rect x="3" y="15" width="6" height="6" rx="1.5" stroke="currentColor" stroke-width="2"/><rect x="15" y="3" width="6" height="6" rx="1.5" stroke="currentColor" stroke-width="2"/><rect x="15" y="15" width="6" height="6" rx="1.5" stroke="currentColor" stroke-width="2"/></svg>
      <span>掃描</span>
    </button>
    <button id="nav-recipe" onclick="switchPage('recipe')">
      <svg width="25" height="25" fill="none" viewBox="0 0 24 24"><path d="M3.5 6.5A2.5 2.5 0 016 4h12a2.5 2.5 0 012.5 2.5v15a.5.5 0 01-.76.43l-5.24-3.27a1.5 1.5 0 00-1.56 0l-5.24 3.27A.5.5 0 015 21.5v-15z" stroke="currentColor" stroke-width="2"/></svg>
      <span>食譜</span>
    </button>
    <button id="nav-profile" onclick="switchPage('profile')">
      <svg viewBox="0 0 24 24" width="25" height="25" fill="none"><circle cx="12" cy="8" r="4" stroke="currentColor" stroke-width="2"/><path d="M4 20a8 8 0 1116 0" stroke="currentColor" stroke-width="2"/></svg>
      <span>個人</span>
    </button>
  </nav>

  <!-- JS主邏輯 -->
  <script>
    // 本地資料結構
    const USER_STORAGE_KEY = 'sp_users';
    const CURRENT_USER_KEY = 'sp_current_user';
    const FEED_KEY = 'sp_feed';
    const SCAN_KEY = 'sp_scan_foods';
    const MARKET_CHAT_KEY = 'sp_market_chats';
    const RECIPE_KEY = 'sp_recipes';

    // 頁面切換與初始化
    function switchPage(page) {
      document.querySelectorAll('.container').forEach(c => c.classList.add('hidden'));
      document.getElementById('page-'+page).classList.remove('hidden');
      document.getElementById('main-header').textContent =
        page==='feed' ? 'SmartPantry 食物管家'
        : page==='market' ? '食物分享市集'
        : page==='scan' ? '食物掃描與管理'
        : page==='recipe' ? '智慧食譜生成器'
        : page==='profile' ? '個人檔案'
        : 'SmartPantry 食物管家';
      document.querySelectorAll('.footer-nav button').forEach(btn => btn.classList.remove('active'));
      if(page!=='login') document.getElementById('nav-'+page).classList.add('active');
      if(page==='feed') { showFeed(); }
      if(page==='market') { showMarket(); }
      if(page==='scan') { showScanFood(); }
      if(page==='profile') { showProfile(); }
    }

    function logout() {
      localStorage.removeItem(CURRENT_USER_KEY);
      localStorage.removeItem(RECIPE_KEY);
      location.reload();
    }

    // -------- 登入/註冊功能 ---------
    function toRegister() {
      document.getElementById('login-form').classList.add('hidden');
      document.getElementById('register-form').classList.remove('hidden');
      document.getElementById('login-success').style.display = 'none';
      document.getElementById('login-error').style.display = 'none';
      clearFormErrors();
    }
    function toLogin() {
      document.getElementById('register-form').classList.add('hidden');
      document.getElementById('login-form').classList.remove('hidden');
      document.getElementById('login-success').style.display = 'none';
      document.getElementById('login-error').style.display = 'none';
      clearFormErrors();
    }
    function showFormError(inputId, errorMessage) {
      const input = document.getElementById(inputId);
      const errorElement = document.getElementById(inputId+'Error');
      if(input && errorElement) {
        input.classList.add('input-error');
        errorElement.textContent = errorMessage;
      }
    }
    function clearFormErrors() {
      document.querySelectorAll('.error-text').forEach(el => el.textContent = '');
      document.querySelectorAll('input').forEach(el => el.classList.remove('input-error'));
    }
    function showLoginSuccess(msg) {
      const el = document.getElementById('login-success');
      el.textContent = msg;
      el.style.display = 'block';
      document.getElementById('login-error').style.display = 'none';
    }
    function showLoginError(msg) {
      const el = document.getElementById('login-error');
      el.textContent = msg;
      el.style.display = 'block';
      document.getElementById('login-success').style.display = 'none';
    }
    function isValidEmail(email) {
      return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
    }
    function getUsers() {
      const usersJson = localStorage.getItem(USER_STORAGE_KEY);
      return usersJson ? JSON.parse(usersJson) : [];
    }
    function saveUsers(users) {
      localStorage.setItem(USER_STORAGE_KEY, JSON.stringify(users));
    }
    function setCurrentUser(user) {
      const userInfo = { id: user.id, name: user.name, email: user.email };
      localStorage.setItem(CURRENT_USER_KEY, JSON.stringify(userInfo));
    }
    function getCurrentUser() {
      const userJson = localStorage.getItem(CURRENT_USER_KEY);
      return userJson ? JSON.parse(userJson) : null;
    }
    document.getElementById('register-form').addEventListener('submit', function(e){
      e.preventDefault(); clearFormErrors();
      const name = document.getElementById('register-name').value.trim();
      const email = document.getElementById('register-email').value.trim();
      const password = document.getElementById('register-password').value;
      const confirm = document.getElementById('register-confirm').value;
      let valid = true;
      if(!name) { showFormError('register-name','請輸入您的姓名'); valid=false; }
      if(!email) { showFormError('register-email','請輸入您的電子郵件'); valid=false; }
      else if(!isValidEmail(email)) { showFormError('register-email','請輸入有效的電子郵件'); valid=false; }
      if(!password) { showFormError('register-password','請輸入密碼'); valid=false; }
      else if(password.length<6) { showFormError('register-password','密碼至少6個字符'); valid=false; }
      if(!confirm || password!==confirm) { showFormError('register-confirm','兩次密碼不一致'); valid=false; }
      if(!valid) return;
      const users = getUsers();
      if(users.some(u=>u.email===email)) { showFormError('register-email','此電子郵件已被註冊'); return;}
      const newUser = { id: Date.now()+'', name, email, password };
      users.push(newUser); saveUsers(users); setCurrentUser(newUser);
      showLoginSuccess('註冊成功，歡迎您！');
      setTimeout(()=>{ showAppAfterLogin(); }, 900);
    });
    document.getElementById('login-form').addEventListener('submit', function(e){
      e.preventDefault(); clearFormErrors();
      const email = document.getElementById('login-email').value.trim();
      const password = document.getElementById('login-password').value;
      let valid = true;
      if(!email) { showFormError('login-email','請輸入您的電子郵件'); valid=false; }
      if(!password) { showFormError('login-password','請輸入您的密碼'); valid=false; }
      if(!valid) return;
      const users = getUsers();
      const user = users.find(u=>u.email===email && u.password===password);
      if(!user) { showLoginError('電子郵件或密碼不正確'); return;}
      setCurrentUser(user);
      showLoginSuccess('登入成功！');
      setTimeout(()=>{ showAppAfterLogin(); }, 700);
    });
    document.getElementById('to-register').onclick = toRegister;
    document.getElementById('to-login').onclick = toLogin;
    document.querySelectorAll('input').forEach(input=>{
      input.addEventListener('input', function(){
        this.classList.remove('input-error');
        const errorElement = document.getElementById(this.id+'Error');
        if(errorElement) errorElement.textContent = '';
      });
    });

    function showAppAfterLogin() {
      document.getElementById('page-login').classList.add('hidden');
      document.getElementById('footer-nav').style.display = 'flex';
      switchPage('feed');
    }
    function checkLogin() {
      if(getCurrentUser()) {
        document.getElementById('page-login').classList.add('hidden');
        document.getElementById('footer-nav').style.display = 'flex';
        switchPage('feed');
      } else {
        document.getElementById('page-login').classList.remove('hidden');
        document.getElementById('footer-nav').style.display = 'none';
        document.querySelectorAll('.container').forEach(c=>{
          if(c.id!=='page-login') c.classList.add('hidden');
        });
      }
    }
    window.addEventListener('DOMContentLoaded', checkLogin);

    // ------- 主頁 Feed 與分享動態 -------
    function showFeed() {
      // 推薦食譜
      let recList = JSON.parse(localStorage.getItem(RECIPE_KEY)||'[]');
      let html = '';
      if(recList.length===0) html = '<div style="color:#888;">暫無推薦食譜，可於「食譜」頁生成</div>';
      else recList.forEach(r=>{
        html += `<div class="card">
          <div style="font-weight:bold;color:#e08e3b;">${r.title}</div>
          <div style="font-size:0.98em;margin:4px 0;">熱量：${r.nutrition?.calories ?? '-'} 大卡</div>
          <div style="font-size:0.97em;">${r.ingredients?.slice(0,2).join('、')??''}...</div>
          <button class="btn-main" style="margin-top:10px;" onclick='showRecipeDetail(${JSON.stringify(r)})'>詳細</button>
        </div>`;
      });
      document.getElementById('feed-recipes').innerHTML = html;
      // 分享動態
      let feed = JSON.parse(localStorage.getItem(FEED_KEY)||'[]');
      if(feed.length===0) document.getElementById('feed-stream').innerHTML = '<div style="color:#888;">暫無分享動態，快來發佈！</div>';
      else document.getElementById('feed-stream').innerHTML = feed.slice().reverse().map(post=>{
        return `<div class="feed-post">
          <div class="feed-avatar">${post.avatar||'👤'}</div>
          <div class="feed-content">
            <div class="feed-user">${post.user}</div>
            <div class="feed-text">${post.text}</div>
            ${post.img?`<img class="feed-image" src="${post.img}" alt="分享圖">`:""}
          </div>
        </div>`;
      }).join('');
    }
    // 發佈分享popup
    function showPostPopup() {
      document.getElementById('post-popup').classList.remove('hidden');
      document.getElementById('post-content').value = '';
      document.getElementById('post-photo').value = '';
    }
    function hidePostPopup() {
      document.getElementById('post-popup').classList.add('hidden');
    }
    function submitPost() {
      let txt = document.getElementById('post-content').value.trim();
      let imgInput = document.getElementById('post-photo');
      let reader = new FileReader();
      if(!txt && !imgInput.files[0]) { alert('請輸入內容或上傳圖片'); return; }
      let pushPost = (imgBase64='') => {
        let cu = getCurrentUser();
        let feed = JSON.parse(localStorage.getItem(FEED_KEY)||'[]');
        feed.push({
          id: Date.now()+'',
          user: cu.name,
          avatar: '👤',
          text: txt,
          img: imgBase64
        });
        localStorage.setItem(FEED_KEY, JSON.stringify(feed));
        hidePostPopup(); showFeed();
      };
      if(imgInput.files && imgInput.files[0]) {
        reader.onload = function(e){ pushPost(e.target.result);}
        reader.readAsDataURL(imgInput.files[0]);
      } else {
        pushPost();
      }
    }

    // ------- 食譜生成器 -------
    document.getElementById('recipeForm').addEventListener('submit', function(e){
      e.preventDefault();
      let age = document.getElementById('age').value.trim();
      if(!age || age<1 || age>120) {
        document.getElementById('age').classList.add('input-error');
        document.getElementById('ageError').textContent = '請輸入1-120之間的有效年齡。';
        return;
      }
      document.getElementById('age').classList.remove('input-error');
      document.getElementById('ageError').textContent = '';
      document.getElementById('loading-message').style.display = 'block';
      document.getElementById('error-message').style.display = 'none';
      setTimeout(()=>{ // 模擬AI處理
        document.getElementById('loading-message').style.display = 'none';
        let sample = [
          {
            "title": "番茄炒蛋",
            "ingredients": ["雞蛋 2顆","番茄 1顆","蔥花 10克","鹽 少許"],
            "steps": ["番茄切塊、蛋打散。","熱鍋加油炒番茄，放蛋液煮熟。","加蔥花鹽拌勻即可。"],
            "nutrition": {calories: 270, protein: 16, carbs: 10, fat: 16, fiber: 2, sodium: 200},
            "tags": ["快速料理","高蛋白"]
          },
          {
            "title": "蔥油雞胸",
            "ingredients": ["雞胸肉 200克","蔥 30克","薑片 3片","鹽胡椒 適量"],
            "steps":["雞胸煮熟撕片。","蔥薑切末熱油淋上，拌入雞胸。"],
            "nutrition": {calories: 220, protein: 38, carbs: 2, fat: 7, fiber: 0, sodium: 180},
            "tags": ["低脂","減脂"]
          },
          {
            "title": "涼拌鮮蔬沙拉",
            "ingredients": ["生菜 50克","小黃瓜 1根","玉米粒 30克","橄欖油 1湯匙"],
            "steps":["蔬菜洗好切塊拌勻。","加橄欖油拌勻即可。"],
            "nutrition": {calories: 95, protein: 3, carbs: 8, fat: 5, fiber: 3, sodium: 40},
            "tags": ["素食","快速料理"]
          }
        ];
        document.getElementById('recipe-section-title').style.display = 'block';
        let html = '';
        sample.forEach(r=>{
          html += `<div class="recipe-card">
            <div style="font-weight:bold;color:#e08e3b; font-size:1.08em;">${r.title}</div>
            <div class="recipe-ingredients"><b>所需食材：</b>${r.ingredients.join("、")}</div>
            <div><b>製作步驟：</b><ol>${r.steps.map(x=>'<li>'+x+'</li>').join('')}</ol></div>
            <div class="recipe-nutrition"><b>營養：</b>
            熱量：${r.nutrition.calories} 大卡，
            蛋白質：${r.nutrition.protein}g，
            碳水化合物：${r.nutrition.carbs}g，
            脂肪：${r.nutrition.fat}g，
            膳食纖維：${r.nutrition.fiber}g，
            鈉：${r.nutrition.sodium}mg
            </div>
            <div class="recipe-tags"><b>標籤：</b>${r.tags.join("、")}</div>
            <button class="btn-main" onclick='addRecipeToProfile(${JSON.stringify(r)})'>加入我的食譜</button>
          </div>`;
        });
        document.getElementById('recipe-container').innerHTML = html;
        localStorage.setItem(RECIPE_KEY, JSON.stringify(sample));
      }, 1200);
    });

    // ------- 食物掃描與管理 -------
    function showScanFood() {
      let foods = JSON.parse(localStorage.getItem(SCAN_KEY)||'[]');
      let html = '';
      if(!foods.length) html = '<div style="color:#888;">暫無食物，請新增！</div>';
      else {
        foods.forEach((f,idx)=>{
          let days = Math.max(0, Math.ceil((new Date(f.expiry)-new Date())/86400000));
          html += `<div class="reminder-card">
            <div style="display:flex;gap:15px;align-items:center;">
              ${f.img ? `<img src="${f.img}" class="market-food-img" style="width:60px;height:60px;">` : ''}
              <div>
                <div class="details">${f.name}</div>
                <div class="expiry">剩餘 ${days} 天</div>
                <div class="qty">數量：${f.qty||1}</div>
              </div>
            </div>
            <button class="btn-main" style="margin-top:8px;" onclick="shareFoodFromScan(${idx})">分享</button>
          </div>`;
        });
      }
      document.getElementById('scan-reminder-list').innerHTML = html;
      document.getElementById('food-name').value='';
      document.getElementById('expiry-date').value='';
      document.getElementById('quantity').value='';
      document.getElementById('food-photo').value='';
    }
    document.getElementById('add-food-btn').onclick = function() {
      let name = document.getElementById('food-name').value.trim();
      let expiry = document.getElementById('expiry-date').value;
      let qty = parseInt(document.getElementById('quantity').value)||1;
      let imgInput = document.getElementById('food-photo');
      if(!name||!expiry) { alert('請輸入完整'); return;}
      let foods = JSON.parse(localStorage.getItem(SCAN_KEY)||'[]');
      if(imgInput.files && imgInput.files[0]) {
        let reader = new FileReader();
        reader.onload = function(e) {
          foods.push({name,expiry,qty,img:e.target.result});
          localStorage.setItem(SCAN_KEY, JSON.stringify(foods));
          showScanFood();
        };
        reader.readAsDataURL(imgInput.files[0]);
      } else {
        foods.push({name,expiry,qty,img:""});
        localStorage.setItem(SCAN_KEY, JSON.stringify(foods));
        showScanFood();
      }
    };
    function shareFoodFromScan(idx) {
      let foods = JSON.parse(localStorage.getItem(SCAN_KEY)||'[]');
      let f = foods[idx];
      let cu = getCurrentUser();
      let feed = JSON.parse(localStorage.getItem(FEED_KEY)||'[]');
      feed.push({
        id: Date.now()+'',
        user: cu.name,
        avatar: '👤',
        text: `分享${f.name} ${f.qty||1}份，有需要可聯絡我！`,
        img: f.img||''
      });
      localStorage.setItem(FEED_KEY, JSON.stringify(feed));
      foods.splice(idx,1);
      localStorage.setItem(SCAN_KEY, JSON.stringify(foods));
      showScanFood();
      alert('已分享至動態！');
    }

    // ------- 市集分享與聊天 -------
    function showMarket() {
      // 市集與分享動態整合（僅展示所有已分享過的食物＋照片）
      let feed = JSON.parse(localStorage.getItem(FEED_KEY)||'[]');
      let html = '';
      if(feed.length === 0) {
        html = '<div style="color:#888;">暫無可分享食物！</div>';
      } else {
        html = feed.slice().reverse().map(f=>`
          <div class="food-card">
            ${f.img? `<img src="${f.img}" alt="Food Image">` : ''}
            <div class="content">
              <div class="title">${f.text.replace(/^分享/,"").replace(/有需要可聯絡我！/,"").trim().substring(0,16)}</div>
              <div class="details">分享者：${f.user}</div>
              <div class="actions">
                <button class="btn-main" onclick="openMarketChat('${f.user}')">聯絡分享者</button>
              </div>
            </div>
          </div>
        `).join('');
      }
      document.getElementById('market-food-list').innerHTML = html;
    }

    // 市集聊天：本地模擬、同一裝置下可留言，實際應用需後端支援
    function openMarketChat(user) {
      let cu = getCurrentUser();
      let chatId = [cu.name, user].sort().join('_');
      document.getElementById('market-chat-modal').classList.remove('hidden');
      document.getElementById('chat-title').textContent = '與分享者 ' + user + ' 聊天';
      document.getElementById('chat-input').value = '';
      renderMarketChat(chatId, cu.name);
      document.getElementById('market-chat-modal').dataset.chatId = chatId;
      document.getElementById('market-chat-modal').dataset.self = cu.name;
    }
    function renderMarketChat(chatId, selfName) {
      let allChats = JSON.parse(localStorage.getItem(MARKET_CHAT_KEY)||'{}');
      let chats = allChats[chatId]||[];
      let msgHtml = chats.map(msg=>`
        <div class="chat-message${msg.user===selfName?' self':''}">${msg.user}：${msg.text}</div>
      `).join('');
      document.getElementById('chat-messages').innerHTML = msgHtml;
      setTimeout(()=> {
        let el = document.getElementById('chat-messages');
        el.scrollTop = el.scrollHeight;
      }, 50);
    }
    function closeMarketChat() {
      document.getElementById('market-chat-modal').classList.add('hidden');
    }
    function sendMarketMessage() {
      let chatId = document.getElementById('market-chat-modal').dataset.chatId;
      let self = document.getElementById('market-chat-modal').dataset.self;
      let txt = document.getElementById('chat-input').value.trim();
      if(!txt) return;
      let allChats = JSON.parse(localStorage.getItem(MARKET_CHAT_KEY)||'{}');
      if(!allChats[chatId]) allChats[chatId] = [];
      allChats[chatId].push({user:self, text:txt, time:Date.now()});
      localStorage.setItem(MARKET_CHAT_KEY, JSON.stringify(allChats));
      document.getElementById('chat-input').value = '';
      renderMarketChat(chatId, self);
    }

    // ------- 個人檔案 -------
    function showProfile() {
      let cu = getCurrentUser();
      document.getElementById('profile-name').textContent = cu?.name||'用戶名稱';
      // 我的食譜
      let recList = JSON.parse(localStorage.getItem(RECIPE_KEY)||'[]');
      let html = '';
      if(!recList.length) html = '<div style="color:#888;">尚未儲存食譜！</div>';
      else recList.forEach(r=>{
        html += `<div class="list-item">
          <div class="title">${r.title}</div>
          <div class="details">熱量：${r.nutrition?.calories} 大卡 | ${r.tags?.join("、")}</div>
        </div>`;
      });
      document.getElementById('profile-recipes').innerHTML = html;
      // 分享紀錄
      let feed = JSON.parse(localStorage.getItem(FEED_KEY)||'[]');
      let html2 = '';
      if(!feed.length) html2 = '<div style="color:#888;">尚未分享過食物！</div>';
      else feed.filter(x=>x.user===cu.name).forEach((f,i)=>{
        html2 += `<div class="list-item">
          <div class="title">分享紀錄 ${i+1}</div>
          <div class="details">${f.text}${f.img?'<img src="'+f.img+'" style="width:30px;height:30px;margin-left:8px;border-radius:6px;">':''}</div>
        </div>`;
      });
      document.getElementById('profile-shared').innerHTML = html2 || '<div style="color:#888;">尚未分享過食物！</div>';
    }
    function showProfileTab(tab) {
      document.querySelectorAll('.tab-content').forEach(e=>e.classList.remove('active'));
      document.getElementById('profile-'+tab).classList.add('active');
      document.querySelectorAll('.tabs button').forEach(e=>e.classList.remove('active'));
      document.getElementById('tab-'+tab).classList.add('active');
    }

    // 首次自動切換登入頁
    if(!getCurrentUser()) {
      switchPage('login');
    }

    // 頁面切換時自動滾頂
    function scrollTopOnPageSwitch() {window.scrollTo(0,0);}
    document.querySelectorAll('.footer-nav button').forEach(btn=>{
      btn.addEventListener('click', scrollTopOnPageSwitch);
    });

    // 聊天視窗按 enter 可送出
    document.getElementById('chat-input').addEventListener('keydown', function(e){
      if(e.key==='Enter'){
        e.preventDefault(); sendMarketMessage();
      }
    });
  </script>
</body>
</html>